<template>
  <Title :text="title">
    <span class="px-2" :class="last > pre_close_px ? 'text-red-500' : 'text-green-600'">
      {{ last }}
    </span>
  </Title>
  <div id="zhishuChart" class="h-52 w-full"></div>
</template>
<script setup>
import echarts from '../utils/echarts';
import axios from 'axios';
import Utils from '../utils/index';
import { ref, onMounted, watch } from 'vue';
const props = defineProps(['code', 'title']);
watch(
  () => props.code,
  (e) => {
    fetchLine(e);
  },
);
const fontSize = 12;
let lineChart = '';
onMounted(() => {
  createChart();
  window.onresize = lineChart.resize;
  setTimeout(() => {
    lineChart.resize();
  }, 1000);
});

function createChart() {
  lineChart = echarts.init(document.getElementById('zhishuChart'));
  lineChart.on('click', function (param) {
    if (param.componentType == 'series') {
      Utils.forwordBk(param.data.plate_id);
    }
  });
}
const list = ref([]);
const pre_close_px = ref(0);
const last = ref();

function fetchMessage() {
  axios.get('https://api.xuangubao.cn/api/messages/todayDaPanYiDong').then((res) => (list.value = res.data.Messages));
}
function fetchLine(code = '000001.SS') {
  axios.get('https://api-ddc-wscn.xuangubao.cn/market/trend?fields=tick_at,close_px&prod_code=' + code).then((res) => {
    let result = res.data.data.candle[code];
    pre_close_px.value = result.pre_close_px.toFixed(2);
    let tmp = result.lines[result.lines.length - 1];
    if (tmp) {
      last.value = tmp[1].toFixed(2);
    }
    renderLine(result.lines, result.pre_close_px.toFixed(2));
  });
}
function fetchData() {
  fetchMessage();
  fetchLine();
}
function renderLine(json, pre_close_px) {
  let chartHeight = lineChart.getHeight() - 20;
  if (json.length == 0) {
    return;
  }
  let dataX = Utils.creatX();
  let data = json.map((e) => {
    return e[1].toFixed(2);
  });
  pre_close_px = parseFloat(pre_close_px);
  let min = Math.min(...data, pre_close_px);
  let max = Math.max(...data, pre_close_px);
  //真最小值
  let cha = Math.abs(max - pre_close_px) >= Math.abs(min - pre_close_px) ? Math.abs(max - pre_close_px) : Math.abs(min - pre_close_px);
  let zmax = cha + pre_close_px + 10;
  let zmin = pre_close_px - cha - 10;

  let markline = [
    {
      yAxis: pre_close_px,
      name: 'pre_close_px',
      // },
      // {
      //   yAxis: max,
      //   name: 'max',
      //   label: {
      //     color: '#ef4444',
      //   },
      // },{
      //   yAxis: min,
      //   name: 'min',
      //   label: {
      //     color: '#16a34a',
      //     position: 'insideEndBottom',
      //   },
    },
  ];

  for (let i = 0; i < list.value.length; i++) {
    let item = list.value[i];
    let time = Utils.formatDateTime(item.CreatedAt, false);
    let index = dataX.findIndex((e) => e == time);
    let tmp = data[index];
    data[index] = {
      value: tmp,
      symbol: 'emptyCircle',
      BkYiDongType: item.BkYiDongType,
      plate_id: item.BkjInfo.Id,
      name: item.BkjInfo.Name,
      desc: time + ' ' + item.BkjInfo.Name + '\n' + item.Title,
      label: {
        // position: i % 4 < 2 ? 'top' : 'bottom',
        position: 'insideTop',
        distance: list.value.length - i,
      },
      // itemStyle: {
      //   color: item.BkYiDongType > 0 ? '#ef4444' : '#16a34a'
      // }
    };
  }

  let showTag = true;
  let lineOption = {
    backgroundColor: '#fff',
    toolbox: {
      show: true,
      feature: {
        myTool1: {
          show: true,
          title: '显示标签',
          icon: 'path://M10 0C4.612 0 0 5.336 0 7c0 1.742 3.546 7 10 7 6.454 0 10-5.258 10-7 0-1.664-4.612-7-10-7Zm0 10a3 3 0 1 1 0-6 3 3 0 0 1 0 6Z',
          onclick: function () {
            showTag = !showTag;
            lineOption.series[0].label.show = showTag;

            lineChart.setOption(lineOption, {
              replaceMerge: ['series'],
            });
          },
        },
      },
    },
    // backgroundColor: '#f5f5f5',
    tooltip: {
      textStyle: {
        fontSize: fontSize,
        color: '#000',
      },
      extraCssText: 'width:50%;white-space:pre-wrap;border-width:2px',
      trigger: 'item',
      axisPointer: {
        type: 'line',
        label: {
          precision: 2,
        },
      },

      formatter: function (params) {
        if (params.data.desc) {
          return params.data.desc;
        } else {
          return params.value;
        }
      },
    },
    xAxis: {
      type: 'category',
      data: dataX,
      axisTick: {
        show: false,
      },
      axisLabel: {
        fontSize: fontSize,
        interval: 0,
        formatter: function (value, index) {
          if (index == 0) {
            return '9:30';
          } else if (index == 60) {
            return '10:30';
          } else if (index == 120) {
            return '11:30/13:00';
          } else if (index == 180) {
            return '14:00';
          } else if (index == 240) {
            return '15:00';
          } else {
            return;
          }
        },
      },
    },
    yAxis: {
      min: zmin,
      max: zmax,
      interval: (zmax - zmin) / 4,
      axisLabel: {
        showMinLabel: false,
        showMaxLabel: false,
        show: true,
        fontSize: fontSize,
        formatter: function (value) {
          return parseInt(value);
        },
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
      splitLine: {
        show: true,
      },
    },
    grid: {
      top: 10,
      bottom: 20,
      left: 45,
      right: '5%',
    },
    visualMap: {
      show: false,
      // dimension: 0,
      pieces: [
        {
          gt: 0,
          lte: pre_close_px,
          color: '#16a34a',
        },
        {
          lte: 90000,
          gt: pre_close_px,
          color: '#ef4444',
        },
      ],
    },
    series: [
      {
        symbol: 'none',
        data: data,
        // showSymbol: false,
        type: 'line',
        markLine: {
          lineStyle: {
            color: 'gray',
          },
          symbol: ['none', 'none'],
          label: {
            position: 'insideEndTop',
            distance: 1,
            fontSize: fontSize,
          },
          data: markline,
        },
        labelLine: {
          show: true,
          lineStyle: {
            // color: 'gray',
            // type: 'dotted'
          },
        },
        labelLayout(params) {
          //计算顺序
          let cha = Math.abs(params.rect.y - params.labelRect.y);
          //框高度
          let labelHeight = params.labelRect.height;
          let y = cha * labelHeight * 1.5;
          while (y >= chartHeight) {
            y = y - chartHeight;
          }

          if (Math.abs(y - params.labelRect.y) < labelHeight) {
            y = y - labelHeight;
          }
          if (y < 20) y = 20;

          return {
            y: y,
            verticalAlign: 'middle',
            align: 'center',
            hideOverlap: false,
            // moveOverlap:'shiftY'
          };
        },
        label: {
          show: true,
          rich: {
            r: {
              color: 'white',
              backgroundColor: '#ef4444',
              padding: 3,
              fontSize: fontSize - 2,
            },
            g: {
              color: 'white',
              backgroundColor: '#16a34a',
              padding: 3,
              fontSize: fontSize - 2,
            },
          },
          formatter: function (params) {
            if (params.data.BkYiDongType > 0) {
              return '{r|' + params.data.name + '}';
            }
            return '{g|' + params.data.name + '}';
          },
        },
      },
    ],
  };
  lineChart.setOption(lineOption);
}
defineExpose({
  fetchData,
  fetchLine,
});
</script>
